﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using Newtonsoft.Json;


namespace WindowsFormsApp1
{
    static class httpMyBackEnd
    {

        private static string url = "http://192.168.10.199/SERVERAPI/";

        static string csrf = null;


        public static async Task<IResult> RefreshCSRF()
        {
            HttpClient http = new HttpClient();

            HttpResponseMessage response = null;

            IResult result = new Result();
            IEnumerable<string> setCookie = null;

            try
            {
                response=await http.GetAsync(url);

                setCookie = response.Headers.GetValues("Set-Cookie");
            }
            catch (Exception ex)
            {
                result.message = "网络不通或者网络错误\r\n"+ex.Message;
                return result;
            }
            
            



            if (setCookie.Count() > 0)
            {
                foreach(var s in setCookie)
                {
                    Match match = Regex.Match(s, @"^csrfToken=([^;]*);");
                    if (match.Success)
                    {
                        csrf = match.Groups[1].Value;
                        result.result = true;
                        result.message = "获取csrf成功";
                        break;
                    }
                }
                
            }

            return result;
           



        }


        public static async Task<IResult> PostJson(string path,object data)
        {


            IResult result = new Result();

            if (csrf == null)
            {
                var re = await RefreshCSRF();
                if (!re.result)
                {
                    return re;
                }
            }


            

          // WebProxy proxyObject = new WebProxy(new Uri("http://127.0.0.1:8888"), true);

            HttpClientHandler message = new HttpClientHandler();
            //proxyObject.BypassProxyOnLocal = false;
            message.UseCookies = false;
            //message.Proxy = proxyObject;
            
            


            HttpClient http = new HttpClient(message);


            
           
            

            string jsonData= JsonConvert.SerializeObject(data);


            var content = new StringContent(jsonData);

            //设置响应头
            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            content.Headers.ContentType.CharSet = "UTF-8";

            content.Headers.Add("Cookie", $"csrfToken={csrf}");

            try
            {
                //发送请求
                var response = await http.PostAsync($"{url}{path}?_csrf={csrf}", content);
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    result.message = $"网络错误:statusCode{response.StatusCode}";
                    return result;
                }


                result.result = true;
                result.message = await response.Content.ReadAsStringAsync();


            }catch(Exception ex)
            {
                result.message = "网络错误:" + ex.Message;
            }

            

            return result;



        }




        


    }
}
